package cn.com.cetccst.compliancecheck.demo.dialog;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;

import cn.com.cetccst.compliancecheck.demo.R;

public class CheckboxListDlg extends AlertDialog.Builder {

    public static void show(Context context, String[] texts, boolean[] checked, Callback callback) {
        CheckListAdapter adapter = new CheckListAdapter(context, texts, checked);
        ListView listView = new ListView(context);
        listView.setAdapter(adapter);

        new CheckboxListDlg(context).setView(listView)
                .setPositiveButton("确定", (dialog, which) -> {
                    callback.handleSelected(adapter.checkedItems);
                })
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .show().setCanceledOnTouchOutside(false);
    }

    public CheckboxListDlg(@NonNull Context context) {
        super(context);
    }

    public interface Callback {
        void handleSelected(boolean[] selected);
    }

    private static class CheckListAdapter extends ArrayAdapter<String> {
        private final Context context;
        private final String[] items;
        public final boolean[] checkedItems;

        public CheckListAdapter(Context context, String[] items, boolean[] checkedItems) {
            super(context, R.layout.checkbox_item, items);
            this.context = context;
            this.items = items;
            this.checkedItems = checkedItems;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.checkbox_item, parent, false);
            }
            CheckBox checkBox = convertView.findViewById(R.id.checkbox);
            TextView textView = convertView.findViewById(R.id.text);
            textView.setText(items[position]);
            checkBox.setOnCheckedChangeListener(null);
            checkBox.setChecked(checkedItems[position]);
            checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> checkedItems[position] = isChecked);
            return convertView;
        }
    }
}
